<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="并发,转载,线程池,">










<meta name="description" content="【转载】- 本文摘自《Java并发编程的艺术-方腾飞》  &amp;nbsp;&amp;nbsp;Java中的线程池是运用场景最多的并发框架，几乎所有的异步或并发执行任务的程序都可以使用线程池。在开发中，合理地使用线程池能够带来3个好处  降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。 提高响应速度。当任务到达时，任务可以不需要等到线程创建就能立即执行。 提高线程的可管理性。线程是稀缺资">
<meta name="keywords" content="并发,转载,线程池">
<meta property="og:type" content="article">
<meta property="og:title" content="Java并发-线程池的原理及使用">
<meta property="og:url" content="https://briarbear.github.io/2018/09/03/Java并发-线程池的原理及使用/index.html">
<meta property="og:site_name" content="briarbear | 熊大">
<meta property="og:description" content="【转载】- 本文摘自《Java并发编程的艺术-方腾飞》  &amp;nbsp;&amp;nbsp;Java中的线程池是运用场景最多的并发框架，几乎所有的异步或并发执行任务的程序都可以使用线程池。在开发中，合理地使用线程池能够带来3个好处  降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。 提高响应速度。当任务到达时，任务可以不需要等到线程创建就能立即执行。 提高线程的可管理性。线程是稀缺资">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://cdn.briarbear.cn/201808031011_271.png">
<meta property="og:image" content="http://cdn.briarbear.cn/201808031019_955.png">
<meta property="og:image" content="http://cdn.briarbear.cn/201808031106_940.png">
<meta property="og:updated_time" content="2019-08-25T08:28:49.581Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java并发-线程池的原理及使用">
<meta name="twitter:description" content="【转载】- 本文摘自《Java并发编程的艺术-方腾飞》  &amp;nbsp;&amp;nbsp;Java中的线程池是运用场景最多的并发框架，几乎所有的异步或并发执行任务的程序都可以使用线程池。在开发中，合理地使用线程池能够带来3个好处  降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。 提高响应速度。当任务到达时，任务可以不需要等到线程创建就能立即执行。 提高线程的可管理性。线程是稀缺资">
<meta name="twitter:image" content="http://cdn.briarbear.cn/201808031011_271.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://briarbear.github.io/2018/09/03/Java并发-线程池的原理及使用/">





  <title>Java并发-线程池的原理及使用 | briarbear | 熊大</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">briarbear | 熊大</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">/- 记录技术成长点滴 -/</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://briarbear.github.io/2018/09/03/Java并发-线程池的原理及使用/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Briar·bear">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/photo.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="briarbear | 熊大">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java并发-线程池的原理及使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-03T13:26:29+08:00">
                2018-09-03
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/09/03/Java并发-线程池的原理及使用/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2018/09/03/Java并发-线程池的原理及使用/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <hr>
<blockquote>
<p>【转载】- 本文摘自《Java并发编程的艺术-方腾飞》</p>
</blockquote>
<p>&nbsp;&nbsp;Java中的线程池是运用场景最多的并发框架，几乎所有的异步或并发执行任务的程序都可以使用线程池。在开发中，合理地使用线程池能够带来3个好处</p>
<ul>
<li><strong>降低资源消耗</strong>。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。</li>
<li><strong>提高响应速度</strong>。当任务到达时，任务可以不需要等到线程创建就能立即执行。</li>
<li><strong>提高线程的可管理性</strong>。线程是稀缺资源，如果无限制地创建，不仅会消耗系统资源，还会降低系统的稳定性，使用线程池可以进行统一分配、调优和监控。但是，要做到合理利用线程池，必须对其实现原理了如指掌。</li>
</ul>
<a id="more"></a>

<h2 id="1-线程池的原理"><a href="#1-线程池的原理" class="headerlink" title="1. 线程池的原理"></a>1. 线程池的原理</h2><p>当向线程池提交一个任务之后，线程池是如何处理这个任务的呢？本节来看一下线程池的主要处理流程，处理流程图如下图所示</p>
<ul>
<li><strong>线程池的主要处理流程</strong></li>
</ul>
<p><img src="http://cdn.briarbear.cn/201808031011_271.png" alt></p>
<ol>
<li>线程池判断核心线程池里的线程是否都在执行任务。如果不是，则创建一个新的工作线程来执行任务。如果核心线程池里的线程都在执行任务，则进入下个流程。</li>
<li>线程池判断工作队列是否已经满。如果工作队列没有满，则将新提交的任务存储在这个工作队列里。如果工作队列满了，则进入下个流程</li>
<li>线程池判断线程池的线程是否都处于工作状态。如果没有，则创建一个新的工作线程来执行任务。如果已经满了，则交给饱和策略来处理这个任务</li>
</ol>
<ul>
<li><code>ThreadPoolExecutor</code>执行<code>execute()</code>方法的示意图</li>
</ul>
<p><img src="http://cdn.briarbear.cn/201808031019_955.png" alt></p>
<p><code>ThreadPooIExecutor</code>执行<code>execute</code>方法分下面4种情况。</p>
<ol>
<li>如果当前运行的线程少于<code>corePooISize</code>，则创建新线程来执行任务（注意，执行这一步骤需要获取全局锁）。</li>
<li>如果运行的线程等于或多于<code>corePooISize</code>，则将任务加入<code>BlockingQueue</code>。</li>
<li>如果无法将任务加入<code>BlockingQueue</code>（队列已满），则创建新的线程来处理任务（注意，执行这一步骤需要获取全局锁）。</li>
<li>如果创建新线程将使当前运行的线程超出<code>maximumPooISize</code>，任务将被拒绝，并调用<code>RejectedExecutionHandler.rejectedExecution()</code>方法。</li>
</ol>
<p><code>ThreadPooIExecutor</code>采取上述步骤的总体设计思路，是为了在执行<code>execute()</code>方法时，尽可能地避免获取全局锁（那将会是一个严重的可伸缩瓶颈）。在<code>ThreadPooIExecutor</code>完成预热之后（当前运行的线程数大于等于<code>corePooISize</code>），几乎所有的<code>execute()</code>方法调用都是执行步骤2，而步骤2不需要获取全局锁。</p>
<p><strong>源码分析：</strong>上面的流程分析让我们很直观地了解了线程池的工作原理，让我们再通过源代码来看看是如何实现的，线程池执行任务的方法如下。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span> <span class="params">(Runnable command)</span></span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(command == <span class="keyword">null</span>)</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException;</span><br><span class="line">    <span class="comment">//如果线程数小于基本线程数，则创建线程并执行当前任务</span></span><br><span class="line">    <span class="keyword">if</span>(poolSize &gt;= corePoolSize || !addIfUnderCorePoolSize(command))&#123;</span><br><span class="line">        <span class="comment">//如线程数大于等于基本线程数或线程创建失败，则将当前任务放到工作队列中。</span></span><br><span class="line">        <span class="keyword">if</span>(runState == RUNNING &amp;&amp; workQueue.offer(command))&#123;</span><br><span class="line">            <span class="keyword">if</span>(runState != RUNNING || poolSize == <span class="number">0</span>)</span><br><span class="line">                ensureQueuedTaskHandled(command);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 如果线程池不处于运行中或任务无法放入队列，并且当前线程数量小于最大允许的线程数量，</span></span><br><span class="line">        <span class="comment">// 则创建一个线程执行任务</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span>(!addIfUnderMaximumPoolSize(command))</span><br><span class="line">        <span class="comment">//抛出 Rej ectedExecutionException异常</span></span><br><span class="line">        reject(command);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>工作线程</strong>：线程池创建线程时，会将线程封装成工作线程Worker，Worker在执行完任务后，还会循环获取工作队列里的任务来执行。我们可以从Worker类的run()方法里看到这点</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        Runnable task = firstTask;</span><br><span class="line">        firstTask = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">while</span>(task != <span class="keyword">null</span> || (task = getTask()) != <span class="keyword">null</span>)&#123;</span><br><span class="line">            runTask(task);</span><br><span class="line">            task = <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">        workerDone(<span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>ThreadPoolExecutor</code>中线程执行任务的示意图如下所示：</p>
<p><img src="http://cdn.briarbear.cn/201808031106_940.png" alt></p>
<p>线程池中的线程执行任务分两种情况，如下</p>
<ol>
<li>在execute()方法中创建一个线程时，会让这个线程执行当前任务。</li>
<li>这个线程执行完上图中1的任务后，会反复从<code>BlockingQueue</code>获取任务来执行</li>
</ol>
<hr>
<h2 id="2-线程池的使用"><a href="#2-线程池的使用" class="headerlink" title="2. 线程池的使用"></a>2. 线程池的使用</h2><h3 id="2-1-线程池的创建"><a href="#2-1-线程池的创建" class="headerlink" title="2.1 线程池的创建"></a>2.1 线程池的创建</h3><p>我们可以通过<code>ThreadPoolExecutor</code>来创建一个线程池</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> ThreadPoolExecutor(corePoolSize, maximumPoolSize,keepAliveTime,TimeUnit,                        BlockingQueue&lt;Runnable&gt;,ThreadFactory,RejectedExecutionHandler)</span><br></pre></td></tr></table></figure>

<p>创建线程池时需要输入几个参数，如下：</p>
<h4 id="1-corePooISize-线程池的基本大小）："><a href="#1-corePooISize-线程池的基本大小）：" class="headerlink" title="1. corePooISize(线程池的基本大小）："></a>1. <code>corePooISize</code>(线程池的基本大小）：</h4><p>当提交一个任务到线程池时，线程池会创建一个线程来执行任务，即使其他空闲的基本线程能够执行新任务也会创建线程，等到需要执行的任务数大于线程池基本大小时就不再创建。如果调用了线程池的<code>prestartAIICoreThreads</code>()方法，线程池会提前创建并启动所有基本线程。</p>
<h4 id="2-maximumPooISize-线程池最大数量）："><a href="#2-maximumPooISize-线程池最大数量）：" class="headerlink" title="2. maximumPooISize(线程池最大数量）："></a>2. <code>maximumPooISize</code>(线程池最大数量）：</h4><p>线程池允许创建的最大线程数。如果队列满了，并且已创建的线程数小于最大线程数，则线程池会再创建新的线程执行任务。值得注意的是，如果使用了无界的任务队列这个参数就没什么效果。</p>
<h4 id="3-keepAliveTime-线程活动保持时间-："><a href="#3-keepAliveTime-线程活动保持时间-：" class="headerlink" title="3. keepAliveTime(线程活动保持时间)："></a>3. <code>keepAliveTime</code>(线程活动保持时间)：</h4><p>线程池的工作线程空闲后，保持存活的时间。所以，如果任务很多，并且每个执行任务的时间比较短，可以调大时间，提高线程的利用率</p>
<h4 id="4-TimeUnit-线程活动保持时间的单位-："><a href="#4-TimeUnit-线程活动保持时间的单位-：" class="headerlink" title="4. TimeUnit(线程活动保持时间的单位)："></a>4. <code>TimeUnit</code>(线程活动保持时间的单位)：</h4><p>可选的单位有天（DAYS）、小时（HOURS）、分钟( MNUTES)、毫秒(MIIIISECONDS)、微秒（MICROSECONDS，千分之一毫秒）和纳秒(NANOSECONDS，千分之一微秒)</p>
<h4 id="5-BlockingQueue（任务队列）："><a href="#5-BlockingQueue（任务队列）：" class="headerlink" title="5. BlockingQueue（任务队列）："></a>5. <code>BlockingQueue</code>（任务队列）：</h4><p>用来保存等待执行的任务的阻塞队列。可以选择以下几个阻塞队列</p>
<ul>
<li><code>ArrayBlockingQueue</code>: 是一个基于数组结构的有界阻塞队列，此队列按FIFO(先进先出)原则对元素进行排序</li>
<li><code>LinkedBlockingQueue</code>：一个基于链表结构的阻塞队列，此队列按FIFO排序元素，吞吐量通常要高于<code>ArrayBlockingQueue</code>。静态工厂方法 <code>Executots.newFixedThreadPool()</code>使用了这个队列。</li>
<li><code>SynchronousQueue</code>：一个不存储元素的阻塞队列，每个插入操作必须等到另一个线程调用移出操作，否则插入操作一直处于阻塞状态，吞吐量通常要高于<code>LinkedBlockingQueue</code>，静态工厂方法<code>Executor.newCachedThreadPool</code>使用了这个队列。</li>
<li><code>PriorityBlockingQueue</code>：一个具有优先级的无限阻塞队列</li>
</ul>
<h4 id="6-ThreadFactory：-用于设置创建线程的工厂"><a href="#6-ThreadFactory：-用于设置创建线程的工厂" class="headerlink" title="6. ThreadFactory：(用于设置创建线程的工厂)"></a>6. <code>ThreadFactory</code>：(用于设置创建线程的工厂)</h4><p>可以通过线程工厂给每个创建出来的线程设置更有意义的名字。使用开源框架<code>guava</code>提供的<code>ThreadFactoryBuilder</code>可以快速给线程池里的线程设置有意义的名字，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> ThreadFactoryBuilder().setNameFormat(<span class="string">"XX-task-%d"</span>).build();</span><br></pre></td></tr></table></figure>

<h4 id="7-RejectedExecutionHandler（饱和策略）："><a href="#7-RejectedExecutionHandler（饱和策略）：" class="headerlink" title="7. RejectedExecutionHandler（饱和策略）："></a>7. <code>RejectedExecutionHandler</code>（饱和策略）：</h4><p>当队列和线程池都满了，说明线程池处于饱和状态，那么必须采取一种策略处理提交的新任务。这个策略默认情况下是<code>AbortPolicy</code>，表示无法处理新任务时抛出异常。在JDK1.5中Java线程池框架提供了4种策略<br>1.<code>AbortPolicy</code>：直接抛出异常。<br>2.<code>CallerRunsPolicy</code>：只用调用者所在线程来运行任务。<br>3.<code>DiscardOldestPolicy</code>：丢弃队列里最近的一个任务，并执行当前任务。<br>4.<code>DiscardPolicy</code>：不处理，丢弃掉。</p>
<hr>
<h3 id="2-2-向线程池提交任务"><a href="#2-2-向线程池提交任务" class="headerlink" title="2.2 向线程池提交任务"></a>2.2 向线程池提交任务</h3><ul>
<li><p>可以使用两个方法向线程池提交任务，分别是<code>execute()</code>和<code>submit()</code>方法</p>
<ol>
<li><p><code>execute()</code>方法用于提交不需要返回值的任务，所以无法判断任务是否被线程池执行成功，可以通过以下代码可知<code>execute()</code>方法输入的是一个<code>Runnable</code>类的实例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">threadsPool.execute(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                      <span class="meta">@Override</span></span><br><span class="line">                        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                            <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>sublime()</code>方法用于提交需要返回值的任务。线程池会返回一个<code>future</code>类型的对象，通过这个<code>future</code>对象可以判断任务是否执行成功，并且可以通过<code>future</code>的<code>get()</code>方法来获取返回值，<code>get()</code>方法会阻塞当前线程知道任务完成，而使用<code>get(long timeout, TimeUnit unit)</code>方法则会一直阻塞当前线程一段时间后立即返回，这时候有可能任务没有执行完。</p>
</li>
</ol>
<hr>
</li>
</ul>
<h3 id="2-3-线程池的关闭"><a href="#2-3-线程池的关闭" class="headerlink" title="2.3 线程池的关闭"></a>2.3 线程池的关闭</h3><ul>
<li>我们可以通过调用线程池的<code>shutdown</code>或<code>shutdownNow</code>方法来关闭线程池，但是它们的实现原理不同;<ul>
<li><code>shutdown</code>的原理是只是将线程池的状态设置成<code>SHUTDOWN</code>状态，然后中断所有没有正在执行任务的线程。</li>
<li><code>shutdownNow</code>的原理是遍历线程池中的工作线程，然后逐个调用线程的<code>interrupt</code>方法来中断线程，所以无法响应中断的任务可能永远无法终止。<code>shutdownNow</code>会首先将线程池的状态设置成<code>STOP</code>，然后尝试停止所有的正在执行或暂停任务的线程，并返回等待执行任务的列表</li>
</ul>
</li>
<li>只要调用了这两个关闭方法的其中一个，<code>isShutdown</code>方法就会返回<code>true</code>。当所有的任务都已关闭后,才表示线程池关闭成功，这时调用<code>isTerminaed</code>方法会返回<code>true</code>。至于我们应该调用哪一种方法来关闭线程池，应该由提交到线程池的任务特性决定，通常调用<code>shutdown</code>来关闭线程池，如果任务不一定要执行完，则可以调用<code>shutdokwnNow</code></li>
</ul>
<hr>
<h2 id="其他链接"><a href="#其他链接" class="headerlink" title="其他链接"></a>其他链接</h2><ul>
<li><a href="http://ifeve.com/java-threadpool/" target="_blank" rel="noopener">聊聊并发(三) Java线程池的分析与使用</a></li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>请我喝杯茶……</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.jpg" alt="Briar·bear 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Briar·bear 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/并发/" rel="tag"># 并发</a>
          
            <a href="/tags/转载/" rel="tag"># 转载</a>
          
            <a href="/tags/线程池/" rel="tag"># 线程池</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/15/计算机网络-OSI七层网络结构/" rel="next" title="计算机网络-OSI七层网络结构">
                <i class="fa fa-chevron-left"></i> 计算机网络-OSI七层网络结构
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/25/hello-world/" rel="prev" title="Hello World">
                Hello World <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/photo.png" alt="Briar·bear">
            
              <p class="site-author-name" itemprop="name">Briar·bear</p>
              <p class="site-description motion-element" itemprop="description">Java程序员成长之路</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">34</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/briarbear" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-线程池的原理"><span class="nav-text">1. 线程池的原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-线程池的使用"><span class="nav-text">2. 线程池的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-线程池的创建"><span class="nav-text">2.1 线程池的创建</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-corePooISize-线程池的基本大小）："><span class="nav-text">1. corePooISize(线程池的基本大小）：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-maximumPooISize-线程池最大数量）："><span class="nav-text">2. maximumPooISize(线程池最大数量）：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-keepAliveTime-线程活动保持时间-："><span class="nav-text">3. keepAliveTime(线程活动保持时间)：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-TimeUnit-线程活动保持时间的单位-："><span class="nav-text">4. TimeUnit(线程活动保持时间的单位)：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-BlockingQueue（任务队列）："><span class="nav-text">5. BlockingQueue（任务队列）：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-ThreadFactory：-用于设置创建线程的工厂"><span class="nav-text">6. ThreadFactory：(用于设置创建线程的工厂)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-RejectedExecutionHandler（饱和策略）："><span class="nav-text">7. RejectedExecutionHandler（饱和策略）：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-向线程池提交任务"><span class="nav-text">2.2 向线程池提交任务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-线程池的关闭"><span class="nav-text">2.3 线程池的关闭</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他链接"><span class="nav-text">其他链接</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Briar·bear</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'briarbear',
            repo: 'gitment',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '2aa927fc78092a27546f7615348dec89f92b9001',
            
                client_id: '512cfb4d4a196b4ee6f6'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

</body>
</html>
